package com.ld.shieldsb.common.web.tag;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;

import com.ld.shieldsb.annotation.util.AnnotationUtil;
import com.ld.shieldsb.common.core.collections.ListUtils;
import com.ld.shieldsb.common.core.util.StringUtils;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;

/**
 * 传入List中某个field的值，输出默认以,号连接的字符串
 * 
 * @ClassName ListFieldTag
 * @author <a href="mailto:donggongai@126.com" target="_blank">吕凯</a>
 * @date 2019年3月28日 下午3:54:16
 *
 */
@EqualsAndHashCode(callSuper = false)
@Data
@Slf4j
public class ListFieldTag extends TagSupportBasicTag {

    /**
     * @Fields serialVersionUID
     */
    private static final long serialVersionUID = 5718857174848876590L;
    private List<Object> value;// 传入的值
    private String field;// 取的field名称
    private String separator = ",";// 取的field名称

    @Override
    public int doStartTag() throws JspException {
        return EVAL_BODY_INCLUDE;
    }

    @Override
    public int doEndTag() throws JspException {
        JspWriter out = pageContext.getOut();// 指定输入流，用于页面输出分页信息、
        StringBuffer sb = new StringBuffer();// 构建StringBuffer对象，用户拼接分页标签
        if (ListUtils.isNotEmpty(value) && StringUtils.isNotBlank(field)) {
            List<String> valList = new ArrayList<>();
            for (Object obj : value) {
                Object value = AnnotationUtil.getModelValue(obj, field);
                valList.add(value == null ? "" : value.toString());
            }
            if (ListUtils.isNotEmpty(valList)) {
                sb.append(String.join(separator, valList));
            }

        }
        try {
            setAttrOrOut(out, sb.toString());
        } catch (IOException e) {
            log.error("", e);
        }
        return EVAL_PAGE;
    }

}
